<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="关键词">
            <a-input style="width: 337px" placeholder="请输入关键词" v-decorator="['searchValue']">
              <a-select
                  slot="addonBefore"
                  v-decorator="['searchType', { initialValue: 10 }]"
                  style="width: 100px"
              >
                <a-select-option
                    v-for="(item, index) in SearchTypeEnum"
                    :key="index"
                    :value="item.value"
                >{{ item.name }}</a-select-option>
              </a-select>
            </a-input>
          </a-form-item>
          <a-form-item label="所属部门" >
            <a-tree-select style="width: 100px"
                :tree-data="deptListTreeData"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                @change="onChangeDept"
                allow-clear
                placeholder="请选择所属部门"
                v-decorator="['zone_id']"
            ></a-tree-select>
          </a-form-item>

          <a-form-item label="会员激活状态">
            <a-select v-decorator="['status', { initialValue: '-1' }]">
              <a-select-option value="-1">全部</a-select-option>
              <a-select-option value="0" >未激活</a-select-option>
              <a-select-option value="1" >已激活</a-select-option>
            </a-select>
          </a-form-item>
<!--          <a-form-item v-if="$module('user-grade')" label="会员等级">
            <a-select v-decorator="['gradeId', { initialValue: 0 }]">
              <a-select-option :value="0">全部</a-select-option>
              <a-select-option
                v-for="(item, index) in gradeList"
                :key="index"
                :value="item.grade_id"
              >{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>-->
          <a-form-item label="注册时间">
            <a-range-picker format="YYYY-MM-DD" v-decorator="['betweenTime']" />
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
          </a-form-item>
        </a-form>
      </a-row>
    </div>

    <s-table
      ref="table"
      rowKey="user_id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
      :total="total"
      :show-total="total => `共${total}条`"
      :showPagination="true"

    >
      <!-- 会员头像 -->
      <span slot="avatar_url" slot-scope="text">
        <div class="avatar">
          <img v-if="text" width="45" height="45" :src="text" alt="用户头像" />
          <img v-else width="45" height="45" src="~@/assets/img/default-avatar.png" alt="用户头像" />
        </div>
      </span>
      <span slot="main_info" slot-scope="item">
        <p>{{ item.nick_name }}</p>
        <p class="c-p">{{ item.mobile }}</p>
      </span>
      <!-- 会员等级 -->
      <!--<span slot="grade" slot-scope="text">
        <a-tag v-if="text">{{ text.name }}</a-tag>
        <span v-else>&#45;&#45;</span>
      </span>-->
      <!-- 余额/积分 -->
      <span slot="balance" slot-scope="text, item">
        <p>
          <span>余额：</span>
          <span class="c-p">{{ text }}</span>
        </p>
        <p>
          <span>个人钱包：</span>
          <span class="c-p">{{ item.wallet }}</span>
        </p>
      </span>
      <!-- 实际消费金额 -->
<!--      <span slot="expend_money" slot-scope="text">
        <span class="c-p">{{ text }}</span>
      </span>-->
      <!-- 注册来源 -->
      <span slot="platform" class="platform" slot-scope="text">
        <platform-icon :name="text" :showTips="true" :iconSize="17" />
      </span>
      <!-- 操作 -->
      <span class="actions" slot="action" slot-scope="item">
        <a
          v-if="$module('market-recharge')"
          v-action:recharge
          @click="handleRecharge(item)"
          title="会员充值"
        >充值</a>
<!--        <a v-action:active @click="handleGrade(item)">会员等级</a>-->
        <a v-action:active @click="handleEdit(item)">编辑</a>
        <a v-action:active @click="handleActive(item)">激活</a>
        <a v-action:cancel @click="handleCancel(item)">冻结</a>
        <a v-action:delete @click="handleDelete(item)">删除</a>
      </span>

    </s-table>
    <p class="total-cont">共{{total}}条</p>

<!--    <GradeForm ref="GradeForm" :gradeList="gradeList" @handleSubmit="handleRefresh" />-->
    <EditForm ref="EditForm"  :zoneList="cascaderOptions" @handleSubmit="handleRefresh" />
    <RechargeForm ref="RechargeForm" @handleSubmit="handleRefresh" />
  </a-card>
</template>

<script>
import { filterModules } from '@/core/app'
import * as Api from '@/api/user'
import * as GradeApi from '@/api/user/grade'
import * as ZoneApi from '@/api/zone'
import { STable } from '@/components'
import PlatformIcon from '@/components/PlatformIcon'
import { GradeForm, EditForm, RechargeForm } from './modules'
import {assignment, inArray} from "@/utils/util";
import {
  DeliveryStatusEnum,
  DeliveryTypeEnum,
  OrderSourceEnum,
  OrderStatusEnum,
  PayStatusEnum, ReceiptStatusEnum
} from "@/common/enum/order";
import {PaymentMethodEnum} from "@/common/enum/payment";
import {Empty} from "ant-design-vue";


// table表头
const columns = filterModules([
  {
    title: '会员ID',
    dataIndex: 'user_id'
  },
  {
    title: '会员头像',
    dataIndex: 'avatar_url',
    scopedSlots: { customRender: 'avatar_url' }
  },
  {
    title: '昵称/手机号',
    scopedSlots: { customRender: 'main_info' }
  },
  {
    title: '员工姓名',
    dataIndex: 'name'
  },
/*  {
    title: '所在区域',
    moduleKey: 'user-zone',
    dataIndex: 'zone.name',
    scopedSlots: { customRender: 'zone' }
  },*/
  {
    title: '所在部门',
    dataIndex: 'zonePath'
  },
  /*{
    title: '会员等级',
    moduleKey: 'user-grade',
    dataIndex: 'grade',
    scopedSlots: { customRender: 'grade' }
  },*/
  {
    title: '会员状态',
    moduleKey: 'user-status',
    dataIndex: 'zt',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '余额',
    dataIndex: 'balance',
    scopedSlots: { customRender: 'balance' }
  },
  /*{
    title: '本月消费金额',
    dataIndex: 'expend_money',
    scopedSlots: { customRender: 'expend_money' }
  },*/
  {
    title: '注册来源',
    dataIndex: 'platform',
    scopedSlots: { customRender: 'platform' }
  },
  {
    title: '注册时间',
    dataIndex: 'create_time'
  },
  {
    title: '操作',
    // dataIndex: 'action',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
])
// 搜索关键词类型枚举
const SearchTypeEnum = [
  { name: '手机号', value: 10 },
  { name: '员工姓名', value: 20 }
]
export default {
  name: 'Index',
  components: {
    EditForm,
    STable,
    GradeForm,
    RechargeForm,
    PlatformIcon
  },
  data () {
    return {
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // table表头
      columns,
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({ ...param, ...this.queryParam })
          .then(response => response.data.list)
      },
      // 会员等级列表
      gradeList: [],
      zoneList: [],
      deptList: [],
      cascaderOptions: [], // 存储转换后的数据，供 Cascader 组件使用
      total: 0,
      // 标签布局属性
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      // 输入框布局属性
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      // 部门列表 树状结构
      deptListTreeData: []
    }
  },
  async created () {
    // 获取会员等级列表
    this.getGradeList()
    this.getZoneList()
    const res = await this.loadData()
    this.total = res.total
  },
  beforeCreate () {
    // 批量给当前实例赋值
    assignment(this, {
      SearchTypeEnum
    })
  },
  methods: {

    // 获取会员等级列表
    getGradeList () {
      GradeApi.all().then(result => {
        this.gradeList = result.data.list
      })
    },
// 获取会员部门列表
    getZoneList () {
      ZoneApi.list().then(result => {
        this.zoneList = result.data.list
        this.convertZoneDataToCascaderOptions()
        // 格式化菜单列表
        this.deptListTreeData  = this.formatTreeData(this.zoneList)

      })
    },
    convertZoneDataToCascaderOptions() {

      // 将原始数据转换为 Cascader 组件所需的格式
      this.cascaderOptions = this.zoneList.map(item => {
        const { zone_id, name, children } = item;
        return {
          value: zone_id,
          label: name,
          // 如果 children 存在且不为空，则递归转换
          children: children && children.length > 0 ? children.map(child => ({
            value: child.zone_id,
            label: child.name,
            // 递归处理子级 children，但在这个示例中，我们假设子级没有更深的嵌套
            // 如果需要，可以在这里添加更深的嵌套处理
          })) : [],
        }
      })

    },
    /**
     * 格式化菜单列表
     */
    formatTreeData (list) {
      const data = []
      list.forEach(item => {
        const newItem = {
          title: item.name,
          key: item.zone_id,
          value: item.zone_id
        }
        if (item.hasOwnProperty('children')) {
          newItem['children'] = this.formatTreeData(item['children'])
        }
        data.push(newItem)
      })
      return data
    },
    // 修改会员等级
    handleGrade (item) {
      this.$refs.GradeForm.handle(item)
    },

    handleEdit (item) {
      this.$refs.EditForm.handle(item)
    },
    // 会员充值
    handleRecharge (item) {
      this.$refs.RechargeForm.handle(item)
    },
    // 用户激活
    handleActive (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要激活该账号吗?',
        content: '激活后该账号将会正常交易',
        onOk () {
          return Api.active({ userId: item.user_id })
              .then(result => {
                app.$message.success(result.message, 1.5)
                app.handleRefresh()
              })
              .finally(result => modal.destroy())
        }
      })
    },
    // 用户冻结
    handleCancel (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要冻结该账号吗?',
        content: '冻结后该账号将会不能正常交易',
        onOk () {
          return Api.cancel({ userId: item.user_id })
              .then(result => {
                app.$message.success(result.message, 1.5)
                app.handleRefresh()
              })
              .finally(result => modal.destroy())
        }
      })
    },
    // 删除记录
    handleDelete (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk () {
          return Api.deleted({ userId: item.user_id })
            .then(result => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => modal.destroy())
        }
      })
    },

    // 确认搜索
    handleSearch (e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },
    onChangeDept (value) {
       console.log('Selected value:', value)
    },
    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh (bool = false) {
      this.$refs.table.refresh(bool)
    }

  }
}
</script>

<style lang="less" scoped>
.total-cont{
 text-align: right;
  margin: -40px 380px auto;
}
.ant-card-body {
  padding: 22px 29px 25px;
}
</style>
